package com.DesignPatten.single;

import java.lang.reflect.Constructor;

/**
 * @ClassName LazyMan
 * @Date 2021/7/27 8:56
 * @Author 李明杰
 * @Description 双重检验锁的懒汉单例
 */

public class LazyMan {
    private LazyMan() {
        System.out.println(Thread.currentThread().getName() + "ok");
    }

    private static LazyMan lazyMan;

    private static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();

                }
            }

        }
        return lazyMan;

    }


    public static void main(String[] args) throws Exception {
        //正常创建
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> LazyMan.getInstance()).start();
//        }
        //反射破坏
        LazyMan lazyMan = LazyMan.getInstance();

        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan lazyMan1 = declaredConstructor.newInstance();
        System.out.println(lazyMan1 == lazyMan);
    }
}
